﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using EDTS.Model.Weixin;
namespace EDTS.Data.Weixin
{
    public class WxRequestCommand
    {
        public static void CreateNew(WxRequestModel model)
        {
            if (model != null)
            {
                using (DBCentre db = new DBCentre())
                {
                    model.CreatedOn = DateTime.Now;
                    model.Status = (int)WxRequestStatus.Waiting;
                    var d = Convertor.ConvertFrom<WxRequest, WxRequestModel>(model);
                    db.DataContext.WxRequests.Add(d);
                    db.DataContext.SaveChanges();
                    model.ID = d.ID;
                }
            }
        }

        public static void ChangeStatus(int id, WxRequestStatus sta,string errlog)
        {
            if (id > 0)
            {
                using (DBCentre db = new DBCentre())
                {
                    var d = db.DataContext.WxRequests.FirstOrDefault(p => p.ID == id);
                    if (d != null)
                    {
                        d.Status = (int)sta;
                        if (sta == WxRequestStatus.Failed && !string.IsNullOrEmpty(errlog))
                            d.ErrorInfo = errlog;
                        db.DataContext.SaveChanges();
                    }
                }
            }
        }

        public static WxRequestCollection Gets(WxRequestQuery sea)
        {
            var ret = new WxRequestCollection();
            if (sea != null)
            {
                using (DBCentre db = new DBCentre())
                {
                    var n = 0;
                    IQueryable<WxRequest> q = db.DataContext.WxRequests;
                    if (sea.Status > 0)
                        q = q.Where(p => p.Status == sea.Status);
                    q = q.OrderBy(p => p.ID);
                    if (sea.PageSize > 0)
                    {
                        n = q.Count();
                        q = q.Skip(sea.PageSize * sea.PageIndex).Take(sea.PageSize);
                    }
                    var lst = q.ToList();
                    ret = Convertor.ConvertCollection<WxRequestModel, WxRequest, WxRequestCollection>(lst);
                    ret.TotalRecordsCount = n == 0 ? lst.Count : n;
                }
            }
            return ret;
        }
    }
}
